<?php
class Clu_Controller_Action_Master extends Zend_Controller_Action 
{
    public $db;
    public $paramsForWidgets = null;
    public $widgetService; //perform queries related to the widget info
    public $viewParams; //view params for the view script
    public $stopPostDipatch = false; 
    public $presenceIdentifier = 1;
    
    public function init()
    {
    	$this->db = Zend_Db_Table::getDefaultAdapter(); //TODO: Remove this when the Models are fine
		$this->widgetService = new Clu_Service_Widget();
    }
    
    public function preDispatch()
    {
    	//1. determine $incomingRequest
		$sess = new Zend_Session_Namespace(CLU_NS);
			
    	if (!isset($sess->masterRequest))
    	{
    		// list of master action for node, not attached to any type of node
    		if ($this->_request->getModuleName() == 'node' && !in_array($this->_request->getActionName(), array(
    				"new-node-type", "edit-node-type", "manage-featured-node", "list-node-types"
    		)))
    			 //blog/master/search; news/master/view 
   				$sess->masterRequest = $this->_request->getParam('type') . '/' .$this->_request->getControllerName() .'/'.$this->_request->getActionName();
    		else 
    		{
        		$sess->masterRequest = $this->_request->getModuleName() . '/' .$this->_request->getControllerName() .'/'.$this->_request->getActionName();
    		}
    	}
		    	
   		//OLD way (2009.11.10)
   		//$sess->masterRequest = $this->_request->getModuleName() . '/' .$this->_request->getControllerName() .'/'.$this->_request->getActionName();		
    	
    	//echo $sess->masterRequest;
    	//2. determine $template from {$incomingRequest, site} from TABLE `action_template` table
    	$template = $this->widgetService->getTemplate(SITE, $sess->masterRequest);
		$this->template = $template;
    	//3. determine $theme
    	if (!isset($sess->userTheme))
	    	$sess->userTheme = Zend_Registry::get('configuration')->general->defaultTheme;
	    	
        //4. set up layout
        $this->widgetService->setupLayout($template, $sess->userTheme);
        
        //TODO: somehow the MasterController still gets its own view object if not set here
        unset($this->view);
        $this->view = $this->widgetService->getView();
    }
    public function postDispatch()
    {
    	if ($this->stopPostDipatch)
    		return;
//	  	//1. determine $incomingRequest
		$sess = new Zend_Session_Namespace(CLU_NS);
		$ajaxWidgetsSess = new Zend_Session_Namespace(AJAX_WIDGETS_NS);
//		//reset ajaxWidgets
		$ajaxWidgetsSess->unsetAll();//->ajaxWidgets = null;
////		$ajaxWidgetsSess->paramsForWidgets = null;
//			
//    	if (!isset($sess->masterRequest))
//    	{
//        	$sess->masterRequest = $this->_request->getModuleName() . '/' .$this->_request->getControllerName() .'/'.$this->_request->getActionName();
//    	}
//    
//    	//2. determine $template from {$incomingRequest, site} from TABLE `action_template` table
//    	$template = $this->widgetService->getTemplate(SITE, $sess->masterRequest);
//		
//    	//3. determine $theme
//    	if (!isset($sess->userTheme))
//	    	$sess->userTheme = Zend_Registry::get('configuration')->general->defaultTheme;
//	    	
//        //4. set up layout
//        $this->widgetService->setupLayout($template, $sess->userTheme);

//    	$layout = Zend_Layout::getMvcInstance();
//    	$layout->setLayoutPath( APP_PATH . '/public/themes/'.$sess->userTheme.'/layouts/scripts');
//	    $layout->setLayout ($template); //common.phtml
    	//5. Get widget list
    	$params = array('site' => SITE, 
    					   'master_request' => $sess->masterRequest, 
    					   'theme' => $sess->userTheme,
    				       'template' => $this->template,
    					   'presence_identifier' => $this->presenceIdentifier,
    					   );
		$widgets = $this->widgetService->getWidgetsInfo($params);
//    	die_a($widgets);
    	foreach ($widgets as $w)
    	{
    		//echo $w['id'] . "." . $w['widget_request'] . "::" . $w['region'] . "-" . $w['weight'] . "::" . $w['script_path'] . "<br/>";
			if ($w['widget_request'] == $w['master_request'])
				$this->renderToHolder($w);
			else if ($w['loading_type'] == 0) //render the widget now 
   				$this->widgetService->addWidget($w, $this->paramsForWidgets);
   			else if ($w['loading_type'] == 1) //ajax load
   			{
   				$this->addAjaxWidget($w);
   			}
    	}
    }
    //by now, we have a list of ajax-able actions like 
	public function addAjaxWidget($widget)
	{
		//store	this ajaxRequest to session
		$ajaxWidgetSess = new Zend_Session_Namespace(AJAX_WIDGETS_NS);
		//add paramsForWidgets if necessary
		if (!isset($ajaxWidgetSess->paramsForWidgets))
			$ajaxWidgetSess->paramsForWidgets = $this->paramsForWidgets;
		
		// key should be placeHolder name
		$name = 'region' . $widget['region'] . '_box';
        $placeHolder = $name.$widget['weight'];
		$ajaxWidgetSess->ajaxWidgets[$placeHolder] = $widget;
		
		//also create a div with id $name to the template
        $holderWeights = Zend_Registry::get('holderWeights');
        $holderWeights[$placeHolder] = $widget['weight']; 
        Zend_Registry::set('holderWeights', $holderWeights);
	}
	
    public function dispatchLoopShutdown(){}
    
    public function __call($method, $args)
    {
    }

    public function renderToHolder ($masterWidgetInfo)
    {
    	$script = '/modules/' . $this->_request->getModuleName() . '/views/scripts/' . $masterWidgetInfo['script_path'] . ".phtml";
    	$region =  $masterWidgetInfo['region'];
    	$weight =  $masterWidgetInfo['weight'];

    	if ($this->widgetService->renderToHolder($this->viewParams, $script, $region, $weight) == false)
    		die("Class: " . get_class($this) . ": region $region and weight $weight already exist");
    }

	public function render($script)
	{
		$this->view->viewParams = $this->viewParams;
		return $this->view->render($script);
	}
    /*
    public function setHolder ($content, $region, $weight = null )
    {
    	if ($this->widgetService->setHolder($content, $regionId, $weight) == false)
    		die(get_class($this) . "with region $region and weight $weight already exist";
    }
	*/
    
    public function renderError($errorCode, $errorMessage)
    {
    	//switch layout to error.phtml
    	//render the layout
    	//no scripts needed
//    	$originalRedirect 
//		header ("Location: " . $this->view->hvnUrl(array("module" => "common", "action" => 'error'), 'nocontroller'));
    	$sess = new Zend_Session_Namespace(CLU_NS);
    	$layout = Zend_Layout::getMvcInstance();
    	
    	$layout->setLayoutPath( APP_PATH . '/public/themes/' . $sess->userTheme . '/layouts/scripts');
//    	$this->widgetService->addWidget($w, $this->paramsForWidgets);
    	
	    $layout->setLayout ('error'); //common.phtml
	    $layout->errorCode = $errorCode;
	    $layout->errorMessage = $errorMessage;
	    $sess = new Zend_Session_Namespace(CLU_NS);
	    $layout->originalRequest = $sess->masterRequest;
	    $layout->originalUri = $_SERVER['REQUEST_URI'];
	    $this->stopPostDipatch = true;
    }

    //public function preDispatch()
    //{
    	//need to determine site, lang, theme, template, region, weight for the masterWidget
    	//
    	//site + lang already available
//    	//1. determine $incomingRequest
//		$sess = new Zend_Session_Namespace(CLU_NS);
//    	if (!isset($sess->masterRequest))
//    	{
//        	$sess->masterRequest = $this->_request->getModuleName() . '/' .$this->_request->getControllerName() .'/'.$this->_request->getActionName();
//    	}
//
//    	//2. determine $template from {$incomingRequest, site} from TABLE `action_template` table
//    	$template = $this->widgetService->getTemplate(SITE, $sess->masterRequest);
//
//    	//determine $theme
//    	if (!isset($sess->userTheme))
//	    	$sess->userTheme = Zend_Registry::get('configuration')->general->defaultTheme;
//    	
//    	//3. determine $region & weight of the master widget 
//    	$this->masterWidgetInfo = $this->widgetService->getWidgetInfo
//    				(array('site' => SITE, 
//    					   'master_request' => $sess->masterRequest, 
//    					   'theme' => $sess->userTheme,
//    				       'template' => $template,
//    					   'widget_request' => $sess->masterRequest));
//    	 die_a($this->masterWidgetInfo);
    	//modules/place/views/scripts/commonTheme/commonLang/commonTemplate/
       	//commonTheme/$lang/$template/
    	//		$region--$controller(widget|ajax|master)--$action(related-city).phtml
    //}

    public function myAction()
    {
    	//
    	//generate $this->viewParams();
    	//render $this->paramsForWidgets;
    	//
    }
    
	public function generatePaginator($select, $pageNumber, $itemsPerPage, $pageRange, $style)
    {
        $paginator = new Zend_Paginator(new Zend_Paginator_Adapter_DbSelect($select));
        $paginator->setItemCountPerPage($itemsPerPage);
        $paginator->setCurrentPageNumber($pageNumber);
        $paginator->setPageRange($pageRange);
        Zend_Paginator::setDefaultScrollingStyle($style);
        return $paginator;
    }
    
}
?>
